package com.zhaojun.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class NioServer {

    public static void main(String[] args) throws Exception {
        ServerSocketChannel sch = ServerSocketChannel.open();
        sch.configureBlocking(false);
        sch.bind(new InetSocketAddress("0.0.0.0",9990));
        Selector selector = Selector.open();
        sch.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.select()>0){

            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iter = selectedKeys.iterator();
            while (iter.hasNext()){
                SelectionKey selectedKey = iter.next();
                System.out.println(selectedKey.interestOps());
                iter.remove();
                if (selectedKey.isAcceptable()){
                    ServerSocketChannel sch0 = (ServerSocketChannel) selectedKey.channel();
                    SocketChannel channel = sch0.accept();
                    System.out.println("--acceptable--");
                    channel.configureBlocking(false);
                    channel.register(selector,SelectionKey.OP_READ);
                }else if(selectedKey.isReadable()){
                    SocketChannel channel = (SocketChannel) selectedKey.channel();
                    ByteBuffer dist=ByteBuffer.allocate(1024);
                    channel.read(dist);
                    dist.flip();
                    String str=Charset.defaultCharset().decode(dist).toString();
                    System.out.println(str);

                    dist.clear();
                    channel.register(selector,SelectionKey.OP_WRITE);
                }else if (selectedKey.isWritable()){
                    SocketChannel channel = (SocketChannel) selectedKey.channel();
                    ByteBuffer src=ByteBuffer.allocate(1024);
                    src.put("hello".getBytes());
                    src.flip();
                    channel.write(src);
                    channel.close();
                }
            }
        }
    }
}
